#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use crate::domain::RecommendBean;
use crate::domain::RecommendQueryRequest;
use crate::serviceimpl::goods_service::find_goods_by_id as service_find_goods_by_id;
use crate::serviceimpl::goods_type_service::find_goods_type_by_id as service_find_goods_type_by_id;
use crate::serviceimpl::recommend_service::activate_all_recommends as service_activate_all_recommends;
use crate::serviceimpl::recommend_service::activate_recommend as service_activate_recommend;
use crate::serviceimpl::recommend_service::add_recommend as service_add_recommend;
use crate::serviceimpl::recommend_service::clone_all_recommends as service_clone_all_recommends;
use crate::serviceimpl::recommend_service::clone_recommend as service_clone_recommend;
use crate::serviceimpl::recommend_service::count_search_recommends_by_fields_records as service_count_search_recommends_by_fields_records;
use crate::serviceimpl::recommend_service::delete_all_recommends as service_delete_all_recommends;
use crate::serviceimpl::recommend_service::delete_recommend as service_delete_recommend;
use crate::serviceimpl::recommend_service::find_recommend_by_id as service_find_recommend_by_id;
use crate::serviceimpl::recommend_service::find_recommend_by_name as service_find_recommend_by_name;
use crate::serviceimpl::recommend_service::list_active_recommends as service_list_active_recommends;
use crate::serviceimpl::recommend_service::list_all_recommends as service_list_all_recommends;
use crate::serviceimpl::recommend_service::search_recommends_by_fields as service_search_recommends_by_fields;
use crate::serviceimpl::recommend_service::search_recommends_by_fields_by_page as service_search_recommends_by_fields_by_page;
use crate::serviceimpl::recommend_service::soft_delete_all_recommends as service_soft_delete_all_recommends;
use crate::serviceimpl::recommend_service::soft_delete_recommend as service_soft_delete_recommend;
use crate::serviceimpl::recommend_service::toggle_one_recommend as service_toggle_one_recommend;
use crate::serviceimpl::recommend_service::toggle_recommend as service_toggle_recommend;
use crate::serviceimpl::recommend_service::update_recommend as service_update_recommend;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::fs;
use tower_http::{trace::TraceLayer};


#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecommendRequest {
	pub id: Option<i64>,
	pub name: Option<String>,
	pub active: Option<bool>,
	pub goods_type_id: Option<i64>,
	pub goods_id: Option<i64>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}

pub fn recommend_controller() -> Router {
	Router::new()
	.route("/listAllRecommends", post(list_all_recommends))
	.route("/updateRecommend", post(update_recommend))
	.route("/deleteRecommend", post(delete_recommend))
	.route("/addRecommend", post(add_recommend))
	.route("/softDeleteRecommend", post(soft_delete_recommend))
	.route("/findRecommendById", post(find_recommend_by_id))
	.route("/findRecommendByName", post(find_recommend_by_name))
	.route("/listActiveRecommends", post(list_active_recommends))
	.route("/deleteAllRecommends", post(delete_all_recommends))
	.route("/softDeleteAllRecommends", post(soft_delete_all_recommends))
	.route("/toggleRecommend", post(toggle_recommend))
	.route("/toggleOneRecommend", post(toggle_one_recommend))
	.route("/searchRecommendsByFieldsByPage", post(search_recommends_by_fields_by_page))
	.route("/activateRecommend", post(activate_recommend))
	.route("/activateAllRecommends", post(activate_all_recommends))
	.route("/exportRecommends", get(export_recommends))
	.route("/exportRecommendsPDF", get(export_recommends_pdf))
	.route("/filterRecommendsExcel", get(filter_recommends_excel))
	.route("/filterRecommendsPDF", get(filter_recommends_pdf))
	.route("/cloneRecommend", post(clone_recommend))
	.route("/cloneAllRecommends", post(clone_all_recommends))
	.route("/checkAccessRecommend", get(check_access_recommend))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}
pub async fn activate_all_recommends(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_activate_all_recommends(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn activate_recommend(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let _result = service_activate_recommend(id).await;
	match _result {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn add_recommend(Json(recommend_request):Json<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let name = recommend_request.name.unwrap_or_default();
	let active = recommend_request.active.unwrap_or_default();
	let goods_type_id = recommend_request.goods_type_id.unwrap_or_default();
	let goods_id = recommend_request.goods_id.unwrap_or_default();

	let recommend = RecommendBean{
	id : id,
	name : name,
	active : active,
	goods_type_id : goods_type_id,
	goods_id : goods_id,
	};
	
	let _result = service_add_recommend(recommend).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn check_access_recommend() ->String {
	r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn clone_all_recommends(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_clone_all_recommends(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn clone_recommend(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let _result = service_clone_recommend(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_all_recommends(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_delete_all_recommends(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_recommend(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let _result = service_delete_recommend(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn export_recommends() ->Response<Body> {
	let list = service_list_all_recommends().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "推荐信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"类型".to_string(),"货品".to_string()];
	let is_images = vec![false,false,false,false,false];
	for recommend in list {
		let goods_type_id = recommend.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}
		let goods_id = recommend.goods_id;
		let mut goods_id_name0 = "".to_string();
		if goods_id > 0 {
			let goods_id_type0 = service_find_goods_by_id(goods_id).await.unwrap();
			if goods_id_type0.id != 0 {
				goods_id_name0 = goods_id_type0.name;
			}
		}

		let row = vec![recommend.id.to_string(),recommend.name,recommend.active.to_string(),goods_type_id_name0,goods_id_name0];
		contents.push(row);
	}

	let full_file_path = "./template/temp/recommends.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=recommends.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn export_recommends_pdf() ->Response<Body> {
	let list = service_list_all_recommends().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "推荐信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"类型".to_string(),"货品".to_string()];
	let is_images = vec![false,false,false,false,false];
	for recommend in list {
		let goods_type_id = recommend.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}
		let goods_id = recommend.goods_id;
		let mut goods_id_name0 = "".to_string();
		if goods_id > 0 {
			let goods_id_type0 = service_find_goods_by_id(goods_id).await.unwrap();
			if goods_id_type0.id != 0 {
				goods_id_name0 = goods_id_type0.name;
			}
		}

		let row = vec![recommend.id.to_string(),recommend.name,recommend.active.to_string(),goods_type_id_name0,goods_id_name0];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);
	
	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=recommends.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_recommends_excel(Query(recommend_query_request):Query<RecommendQueryRequest>) ->Response<Body> {
	let list = service_search_recommends_by_fields(recommend_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "推荐信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"类型".to_string(),"货品".to_string()];
	let is_images = vec![false,false,false,false,false];
	for recommend in list {
		let goods_type_id = recommend.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}
		let goods_id = recommend.goods_id;
		let mut goods_id_name0 = "".to_string();
		if goods_id > 0 {
			let goods_id_type0 = service_find_goods_by_id(goods_id).await.unwrap();
			if goods_id_type0.id != 0 {
				goods_id_name0 = goods_id_type0.name;
			}
		}

		let row = vec![recommend.id.to_string(),recommend.name,recommend.active.to_string(),goods_type_id_name0,goods_id_name0];
		contents.push(row);
	}

	let full_file_path = "./template/temp/recommends.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=recommends.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_recommends_pdf(Query(recommend_query_request):Query<RecommendQueryRequest>) ->Response<Body> {
	let list = service_search_recommends_by_fields(recommend_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "推荐信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"类型".to_string(),"货品".to_string()];
	let is_images = vec![false,false,false,false,false];
	for recommend in list {
		let goods_type_id = recommend.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}
		let goods_id = recommend.goods_id;
		let mut goods_id_name0 = "".to_string();
		if goods_id > 0 {
			let goods_id_type0 = service_find_goods_by_id(goods_id).await.unwrap();
			if goods_id_type0.id != 0 {
				goods_id_name0 = goods_id_type0.name;
			}
		}

		let row = vec![recommend.id.to_string(),recommend.name,recommend.active.to_string(),goods_type_id_name0,goods_id_name0];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=recommends.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn find_recommend_by_id(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let recommend = service_find_recommend_by_id(id).await;
	match recommend {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(recommend) => {
			let json = serde_json::to_string_pretty(&recommend).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn find_recommend_by_name(Form(recommend_request):Form<RecommendRequest>) ->String {
	let name = recommend_request.name.unwrap_or_default();
	let recommend = service_find_recommend_by_name(name).await;
	match recommend {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(recommend) => {
			let json = serde_json::to_string_pretty(&recommend).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_recommends() ->String {
	let recommends = service_list_active_recommends().await;
	match recommends {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(recommends) => {
			let json = serde_json::to_string_pretty(&recommends).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn list_all_recommends() ->String {
	let recommends = service_list_all_recommends().await;
	match recommends {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(recommends) => {
			let json = serde_json::to_string_pretty(&recommends).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn search_recommends_by_fields_by_page(Form(recommend_query_request):Form<RecommendQueryRequest>) ->String {
	let recommends = service_search_recommends_by_fields_by_page(recommend_query_request.clone()).await;
	let total = service_count_search_recommends_by_fields_records(recommend_query_request.clone()).await.unwrap().count_num;
	match recommends {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(recommends) => {
			let json = serde_json::to_string_pretty(&recommends).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("total".to_string(), Value::from(total));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_all_recommends(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_soft_delete_all_recommends(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_recommend(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let _result = service_soft_delete_recommend(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_one_recommend(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let _result = service_toggle_one_recommend(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_recommend(Form(recommend_request):Form<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let _result = service_toggle_recommend(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn update_recommend(Json(recommend_request):Json<RecommendRequest>) ->String {
	let id = recommend_request.id.unwrap_or_default();
	let name = recommend_request.name.unwrap_or_default();
	let active = recommend_request.active.unwrap_or_default();
	let goods_type_id = recommend_request.goods_type_id.unwrap_or_default();
	let goods_id = recommend_request.goods_id.unwrap_or_default();
	let _current_recommend = service_find_recommend_by_id(id).await.unwrap();

	let recommend = RecommendBean{
	id : id,
	name : name,
	active : active,
	goods_type_id : goods_type_id,
	goods_id : goods_id,
	};
	
	let _result = service_update_recommend(recommend).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

